package Facade

import (
	"Volta/Core/Facade/ServiceContainer"
	"Volta/Core/Facade/ServiceInterface"
	"errors"
	"fmt"
	"reflect"
)

//. 比较复杂交互，service互相多次调用的逻辑建议在facade内编写-------------------------------------------
var Accessor facadeAccessor

type facadeAccessor struct {
	GoMysql   ServiceInterface.MysqlDriverInterface   `container:"CORAL_MYSQL"`
	GoRedis   ServiceInterface.RedisDriverInterface   `container:"CORAL_REDIS"`
	GoElastic ServiceInterface.ElasticDriverInterface `container:"CORAL_ELASTIC"`
	Config    ServiceInterface.ConfigInterface        `container:"CORAL_CONFIG"`
	Lua       ServiceInterface.LuaInterface           `container:"CORAL_LUA"`
	GoOss     ServiceInterface.OssInterface           `container:"CORAL_OSS"`
}

//. worker实体到facade接口中
func Register() (err error) {
	err = facadeManager()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	return
}

func facadeManager() (err error) {
	rfType := reflect.TypeOf(&Accessor).Elem()
	proType := reflect.ValueOf(&Accessor).Elem()
	kd := proType.Kind()
	if kd != reflect.Struct {
		err = errors.New("expect facade struct")
		return err
	}
	num := proType.NumField()
	//.快捷注册
	for i := 0; i < num; i++ {
		tag := rfType.Field(i).Tag.Get("container")
		service, err := ServiceContainer.Making(tag)
		if err != nil {
			err = errors.New("Not Fount Facade Instance " + tag)
			return err
		}
		proType.Field(i).Set(reflect.ValueOf(service))
	}
	return
}
